package com.hmall.search;

import cn.hutool.json.JSONUtil;
import com.hmall.search.domain.po.ItemDoc;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * @create: 张曦文
 * 日期 :2025/11/10 11:55
 * 功能 :
 **/
@SpringBootTest
public class test {
    @Autowired
    private RestHighLevelClient client;

    @Test
    public void es() throws Exception {
        SearchRequest request = new SearchRequest("items");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        //searchSourceBuilder.query(QueryBuilders.matchQuery("name","小米手机"));
        // searchSourceBuilder.query(QueryBuilders.termQuery("name","小米手机"));
        //searchSourceBuilder.query(QueryBuilders.rangeQuery("price").gte(1000).lte(2000));

        searchSourceBuilder.query(QueryBuilders.boolQuery()
                .must(QueryBuilders.matchQuery("name","小米"))
                .filter(QueryBuilders.rangeQuery("price").gte(100).lte(2000)));

        searchSourceBuilder.sort("price", SortOrder.DESC);

        searchSourceBuilder.from(2);
        searchSourceBuilder.size(2);

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);

        request.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);

        SearchHits searchHits = searchResponse.getHits();
        long value = searchHits.getTotalHits().value;
        System.out.println("查询到的数据为----" + value);

        SearchHit[] searchHitsHits = searchHits.getHits();
        for (SearchHit hit : searchHitsHits) {
            String sourceAsString = hit.getSourceAsString();
            ItemDoc itemDoc = JSONUtil.toBean(sourceAsString, ItemDoc.class);
            System.out.println(itemDoc);
        }
    }
}
